package cn.codeforfun.user;

import cn.codeforfun.generator.model.Resource;
import cn.codeforfun.generator.model.User;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wangbin
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class UserVO extends User implements UserDetails {
    private static final long serialVersionUID = 5616781253343969419L;

    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    private String password;

    private List<Resource> resourceList;

    public static UserVO from(User user) {
        UserVO result = new UserVO();
        BeanUtils.copyProperties(user, result);
        return result;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (ObjectUtils.isEmpty(resourceList)) {
            return new ArrayList<>();
        }
        return resourceList.stream().map(s -> (GrantedAuthority) s::getName).collect(Collectors.toList());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return super.getEnable() != null && super.getEnable();
    }
}
